package com.jctrip.hotel.source.service.rezen;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Author henry
 * @Date 2023/8/11 09:44
 * @Description
 */
public class RezenSigUtils {
    private static final String CONTENT_CHARSET = "UTF-8";
    private static final String HMAC_ALGORITHM = "HmacSHA256";

    public static String genSign(String secretKey, String secretId, Long timestamp, String param) {
        String[] params = {secretKey, secretId,
                String.valueOf(timestamp), param};
        List<String> paramsList = new
                ArrayList<>(Arrays.asList(params));
        Collections.sort(paramsList);
        StringBuilder signing = new StringBuilder();
        paramsList.forEach(signing::append);
        return hmacSHA256(secretKey, signing.toString());
    }

    private static String hmacSHA256(String secret, String signing) {
        try {
            Mac mac1 = Mac.getInstance(HMAC_ALGORITHM);
            byte[] hash;
            SecretKeySpec secretKey = new
                    SecretKeySpec(secret.getBytes(CONTENT_CHARSET),
                    mac1.getAlgorithm());
            mac1.init(secretKey);
            hash = mac1.doFinal(signing.getBytes(CONTENT_CHARSET));
            return new String(Base64.getEncoder().encode(hash));
        } catch (Exception e) {
            throw new RuntimeException("签名失败");
        }
    }
}
